package com.cml.dm.admin.service.impl;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cml.dm.admin.entity.DmExeLogger;
import com.cml.dm.admin.entity.DmMetadata;
import com.cml.dm.admin.model.FileStoreModel;
import com.cml.dm.admin.service.EncryptionFactory;
import com.cml.dm.admin.service.FileCompressFactory;
import com.cml.dm.admin.service.StoreFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.List;

@Component
public class FileStoreService implements StoreFactory<FileStoreModel> {

    private static final Logger logger = LoggerFactory.getLogger(FileStoreService.class);

    @Autowired
    private EncryptionFactory encryptionFactory;
    @Autowired
    private FileCompressFactory fileCompressFactory;

    @Override
    public String store(FileStoreModel storeModel) {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            //备份的路径
            String backupPath = storeModel.getBackupPath();
            if(StringUtils.isBlank(backupPath)){
                backupPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()+"backup";
                logger.info("========= backupPath：{}", backupPath);
            }
            File backupDir = new File(backupPath);
            if(!backupDir.exists()){
                //如果路径文件不存在，先创建
                backupDir.mkdirs();
            }
            String name = "%s-%s-%s";
            //备份的文件名：任务名-组织id-时间戳.json
            String backupFileName = String.format(name,storeModel.getTaskId(),storeModel.getOrgId(),String.valueOf(System.currentTimeMillis()));
            String fileName = backupFileName+".json";
            File file = File.createTempFile(backupFileName,".json");
            JSONObject dJson = new JSONObject();
            dJson.put("taskId",storeModel.getTaskId());
            dJson.put("version",storeModel.getVersion());
            dJson.put("orgId",storeModel.getOrgId());
            dJson.put("date", storeModel.getDate().toString());
            dJson.put("datas",storeModel.getDatas());
            String fc = JSONObject.toJSONStringWithDateFormat(dJson,"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue);
            fos = new FileOutputStream(file);
            byte[] eb = encryptionFactory.encode(fc.getBytes());
            fos.write(eb);
            fos.flush();
            fis = new FileInputStream(file);
            //生成压缩文件
            return fileCompressFactory.compress(fis,fileName,backupPath+"/"+fileName.replace(".json",".zip"));
        }catch (Exception e){
            String s = String.format("TaskId:%s, orgId:%s 备份失败", storeModel.getTaskId(), storeModel.getOrgId());
            logger.error(s,e);
            throw new RuntimeException(s);
        }finally {
            IoUtil.close(fos);
            IoUtil.close(fis);
        }
    }
}
